package studio.raptor.databus.graph.controller;

import java.util.Set;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import studio.raptor.databus.graph.common.Idempotent;
import studio.raptor.databus.graph.domain.Event;
import studio.raptor.databus.graph.domain.Events;
import studio.raptor.databus.graph.service.EventService;


@RestController
@RequestMapping(value = "/event", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class EventController {

  private static final Logger log = LoggerFactory.getLogger(EventController.class);

  @Autowired
  EventService eventService;

  /**
   * 批量保存事件到数据库，并建立事件之间的关联关系
   */
  @PostMapping(value = "/batchAdd")
  @Idempotent
  public void batchAddEvents(@RequestBody @Valid Events events) {
    eventService.addEvents(events);
  }

  /**
   * 保存事件到数据库，并建立事件之间的关联关系
   */
  @PostMapping(value = "/add")
  @Idempotent
  public void addEvent(@RequestBody @Valid Event event) {
    eventService.addEvent(event);
  }

  /**
   * 更新事件状态
   */
  @PostMapping(value = "/update")
  @Idempotent
  public void update(@RequestBody Event event) {
    eventService
        .updateEventStatus(event.getEventId(), event.getName(), event.getCode(), event.getStatus());
  }

  /**
   * 批量更新事件状态
   */
  @PostMapping(value = "/batchUpdate")
  @Idempotent
  public void batchUpdate(@RequestBody Events events) {
    eventService.updateEvents(events);
  }

  /**
   * 删除事件
   */
  @PostMapping(value = "/delete")
  @Idempotent
  public void delete(@RequestBody Event event) {
    eventService.deleteEventNode(event.getCode(), event.getEventId(), event.getName());
  }

  /**
   * 批量删除事件
   */
  @PostMapping(value = "/batchDelete")
  @Idempotent
  public void batchDelete(@RequestBody Events events) {
    eventService.deleteEvents(events);
  }

  /**
   * 获取可以被发送的事件节点
   *
   * @param code 接口编码
   * @param limit 获取最大值
   */
  @GetMapping(value = "/query")
  public Set<String> query(@RequestParam(value = "code") String code,
      @RequestParam(value = "limit", defaultValue = "30") int limit,
      @RequestParam(value = "status", defaultValue = "w") String status) {
    return eventService.fetchEvent(code, status, limit);
  }


}
